package com.antd.gateway.handler;

import cn.hutool.core.util.StrUtil;
import com.antd.common.core.constant.AntdConstant;
import com.antd.common.core.util.CaptchaUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2020/11/19 17:49
 */
@Slf4j
@Component
@AllArgsConstructor
public class ImageCodeHandler implements HandlerFunction<ServerResponse> {
    private final StringRedisTemplate redisTemplate;
    @Override
    public Mono<ServerResponse> handle(ServerRequest request) {
        // 图片输出流
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        // 生成图片验证码
        BufferedImage image = CaptchaUtil.createImage();
        // 生成文字验证码
        String randomText = CaptchaUtil.drawRandomText(image);
        // 保存到验证码到 redis 有效期两分钟
        Optional<String> queryParam = request.queryParam("t");
        String t= queryParam.orElse(StrUtil.EMPTY);
        redisTemplate.opsForValue().set(AntdConstant.IMAGE_KEY+t,randomText.toLowerCase(), 2L,TimeUnit.MINUTES);
        try {
            ImageIO.write(image, "jpeg", os);
        } catch (IOException e) {
            log.error("验证码生成失败", e);
            return Mono.error(e);
        }
        return ServerResponse
                .status(HttpStatus.OK)
                .contentType(MediaType.IMAGE_JPEG)
                .body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));
    }
}
